<template>
	<a-drawer
		:title="formData.id ? '编辑柜子信息' : '增加柜子信息'"
		:width="600"
		:visible="visible"
		:destroy-on-close="true"
		:footer-style="{ textAlign: 'right' }"
		@close="onClose"
	>
		<a-form ref="formRef" :model="formData" :rules="formRules" layout="vertical">
			<a-row :gutter="24">
				<a-col :span="12">
					<a-form-item label="组柜：" name="cabinetGroupId">
						<a-select
							v-model:value="formData.cabinetGroupId"
							placeholder="请选择组柜"
							:options="cabinetGroupOptions"
							@change="changeCabinetGroup"
							allow-clear
						/>
					</a-form-item>
				</a-col>
				<a-col :span="12">
					<a-form-item label="柜子编号：" name="cabinetCode">
						<a-input
							v-model:value="formData.cabinetCode"
							placeholder="请输入柜子编号"
							allow-clear
							:disabled="formData.id"
						/>
					</a-form-item>
				</a-col>
			</a-row>
			<a-row :gutter="24">
				<a-col :span="12">
					<a-form-item label="柜子名称：" name="cabinetName">
						<a-input
							v-model:value="formData.cabinetName"
							placeholder="请输入柜子名称"
							allow-clear
							:disabled="formData.id"
						/>
					</a-form-item>
				</a-col>
				<a-col :span="12">
					<a-form-item label="柜子类型：" name="cabinetTypeId">
						<a-select
							v-model:value="formData.cabinetTypeId"
							placeholder="请选择柜子类型"
							:options="cabinetTypeOptions"
							allow-clear
							:disabled="formData.id"
						/>
					</a-form-item>
				</a-col>
			</a-row>
			<a-row :gutter="24">
				<a-col :span="12">
					<a-form-item label="设备硬件标识：" name="cabinetIdentify">
						<a-input v-model:value.trim="formData.cabinetIdentify" placeholder="请输入设备硬件标识" :disabled="true" />
					</a-form-item>
				</a-col>
				<a-col :span="12">
					<a-form-item label="开锁模式：" name="cabinetLockType">
						<a-select
							v-model:value="formData.cabinetLockType"
							:default-value="1"
							placeholder="请选择开锁模式"
							:options="cabinetLockTypeOptions"
							allow-clear
						/>
					</a-form-item>
				</a-col>
			</a-row>
			<a-row :gutter="24">
				<a-col :span="12">
					<a-form-item label="资产编号：" name="assetCode">
						<a-input v-model:value.trim="formData.assetCode" placeholder="请输入资产编号" allow-clear />
					</a-form-item>
				</a-col>
				<a-col :span="12">
					<a-form-item label="存放区域：" name="areaId">
						<a-select
							v-model:value="formData.areaId"
							show-search
							:filter-option="filterOption"
							placeholder="请选择存放区域"
							:options="areaOptions"
							allow-clear
							@change="changeArea"
						/>
					</a-form-item>
				</a-col>
			</a-row>

			<a-row :gutter="24">
				<a-col :span="12">
					<a-form-item label="存放楼宇：" name="buildingId">
						<a-select
							v-model:value="formData.buildingId"
							show-search
							:filter-option="filterOption"
							placeholder="请选择存放楼宇"
							:options="buildingOptions"
							allow-clear
							@change="changeBuilding"
						/>
					</a-form-item>
				</a-col>
				<a-col :span="12">
					<a-form-item label="存放房间：" name="roomId">
						<a-select
							v-model:value="formData.roomId"
							show-search
							:filter-option="filterOption"
							placeholder="请选择存放房间"
							:options="roomOptions"
							allow-clear
						/>
					</a-form-item>
				</a-col>
			</a-row>

			<a-row :gutter="24">
				<a-col :span="12">
					<a-form-item label="所属组织：" name="orgId">
						<a-tree-select
							v-model:value="formData.orgId"
							style="width: 100%"
							:dropdown-style="{ maxHeight: '400px', overflow: 'auto' }"
							placeholder="请选择所属组织"
							allow-clear
							tree-default-expand-all
							:tree-data="treeData"
							:field-names="{
								children: 'children',
								label: 'name',
								value: 'id'
							}"
							selectable="false"
							tree-line
						></a-tree-select>
					</a-form-item>
				</a-col>
				<a-col :span="12">
					<a-form-item label="管理员：" name="adminUserIds">
						<a-button type="link" size="small" style="padding-left: 0" @click="openSelector">选择</a-button>
						<a-tag color="orange" v-for="item in selectedAdminUsers" :key="item.id">
							{{ item.name }}
						</a-tag>
					</a-form-item>
				</a-col>
			</a-row>

			<a-row :gutter="24">
				<a-col :span="12">
					<a-form-item label="盘库周期单位：" name="makingInventoryUnit">
						<a-select
							v-model:value="formData.makingInventoryUnit"
							placeholder="请选择盘库周期类型"
							:options="makingInventoryUnitOptions"
							allow-clear
						/>
					</a-form-item>
				</a-col>
				<a-col :span="12">
					<a-form-item label="盘库周期：" name="makingInventoryCycle">
						<a-input-number
							v-model:value="formData.makingInventoryCycle"
							placeholder="请输入盘库周期"
							:addon-after="['天', '小时'][formData.makingInventoryUnit]"
							:precision="0"
							:min="1"
							allow-clear
							:disabled="formData.makingInventoryUnit !== 0 && formData.makingInventoryUnit !== 1"
						/>
					</a-form-item>
				</a-col>
			</a-row>

			<a-row :gutter="24">
				<a-col :span="12">
					<a-form-item label="权限最大天数(不填则无限制)：" name="maxPermDays">
						<a-input-number
							v-model:value="formData.maxPermDays"
							placeholder="请输入权限最大天数"
							addon-after="天"
							:precision="0"
							:min="0"
							allow-clear
						/>
					</a-form-item>
				</a-col>
				<a-col :span="12">
					<a-form-item label="备注：" name="remark">
						<a-textarea v-model:value="formData.remark" placeholder="请输入备注" allow-clear />
					</a-form-item>
				</a-col>
			</a-row>

			<a-form-item label="柜子描述：" name="cabinetComment">
				<xn-editor v-model="formData.cabinetComment" placeholder="请输入柜子描述" :height="200"></xn-editor>
			</a-form-item>
		</a-form>
		<template #footer>
			<a-button style="margin-right: 8px" @click="onClose">关闭</a-button>
			<a-button type="primary" @click="onSubmit" :loading="submitLoading">保存</a-button>
		</template>

		<admin-user-selector-plus
			ref="AdminUserSelectorPlus"
			page-url="/sys/role/userSelectorForRole"
			role-no="cabAdmin"
			@onBack="afterSelectUser"
		/>
	</a-drawer>
</template>

<script setup name="bizCabinetInfoForm">
	import XnEditor from '@/components/Editor/index.vue'
	import { cloneDeep } from 'lodash-es'
	import { required } from '@/utils/formRules'
	import bizCabinetInfoApi from '@/api/biz/bizCabinetInfoApi'
	import bizCabinetTypeApi from '@/api/biz/bizCabinetTypeApi'
	import bizCabinetGroupApi from '@/api/biz/bizCabinetGroupApi'
	import adminUserSelectorPlus from '@/components/Selector/adminUserSelectorPlus.vue'
	import bizLocationRoomApi from '@/api/biz/bizLocationRoomApi'
	import bizLocationAreaApi from '@/api/biz/bizLocationAreaApi'
	import bizLocationBuildingApi from '@/api/biz/bizLocationBuildingApi'
	import bizOrgApi from '@/api/biz/bizOrgApi'
	import { useRouter } from 'vue-router'
	import tool from '@/utils/tool'
	// 抽屉状态
	const visible = ref(false)
	const fromCabinetGroup = ref(false) // 是否从组柜功能跳转过来
	let AdminUserSelectorPlus = ref()
	const emit = defineEmits({ successful: null })
	const areaOptions = ref([])
	const buildingOptions = ref([])
	const roomOptions = ref([])
	const treeData = ref([])
	const formRef = ref()
	const userInfo = tool.data.get('USER_INFO')
	// 表单数据
	const formData = ref({})
	const cabinetTypeOptions = ref([])
	const cabinetGroupOptions = ref([])
	const submitLoading = ref(false)
	//选择的超管人员
	const selectedAdminUsers = ref([])

	const makingInventoryUnitOptions = ref([
		{
			label: '按天',
			value: 0
		},
		{
			label: '按小时',
			value: 1
		}
	])

	// 柜子的开锁模式：1-单人开锁 2-双人开锁 3-双人开锁，至少一个管理员
	const cabinetLockTypeOptions = ref([
		{
			label: '单人开锁',
			value: 1
		},
		{
			label: '双人开锁',
			value: 2
		},
		{
			label: '双人开锁，至少一个管理员',
			value: 3
		}
	])
	// 打开抽屉
	const onOpen = (record) => {
		visible.value = true
		if (record) {
			let recordData = cloneDeep(record)
			formData.value = Object.assign({}, recordData)
			if (recordData.adminUserIds) {
				let adminUserNames = recordData.adminUserNames.split(',')
				recordData.adminUserIds.split(',').forEach((userId, index) => {
					selectedAdminUsers.value.push({
						id: userId,
						name: adminUserNames[index]
					})
				})
			}
		} else {
			formData.value.adminUserIds = userInfo.id
			selectedAdminUsers.value = [
				{
					id: userInfo.id,
					name: userInfo.name
				}
			]
		}

		bizLocationAreaApi.bizLocationAreaList({}).then((res) => {
			areaOptions.value = res.map((item) => {
				return {
					label: item.name,
					value: item.id
				}
			})
		})
		bizLocationBuildingApi.bizLocationBuildingList({}).then((res) => {
			buildingOptions.value = res.map((item) => {
				return {
					label: item.name,
					value: item.id
				}
			})
		})
		loadLocationRoomList()
		// 获取机构树并加入顶级
		bizOrgApi.orgTree().then((res) => {
			treeData.value = [
				{
					id: 0,
					parentId: '-1',
					name: '顶级',
					children: res
				}
			]
		})

		bizCabinetTypeApi.bizCabinetTypeList({}).then((res) => {
			cabinetTypeOptions.value = res.map((item) => {
				return {
					label: item.name,
					value: item.id
				}
			})
		})
		bizCabinetGroupApi.bizCabinetGroupList({}).then((res) => {
			console.log(res)
			cabinetGroupOptions.value = res.map((item) => {
				return {
					label: `${item.cabinetGroupCode}-${item.cabinetGroupName}`,
					value: item.id,
					cabinetIdentify: item.cabinetIdentify
				}
			})
		})
	}
	// 打开人员选择器，选择主管
	const openSelector = () => {
		let userIds = selectedAdminUsers.value.map((user) => user.id)
		console.log('userIds=', userIds)
		AdminUserSelectorPlus.value.showUserPlusModal(userIds)
	}
	// 人员选择器回调
	const afterSelectUser = (value) => {
		selectedAdminUsers.value = value
		formData.value.adminUserIds = value.map((item) => item.id).join(',')
	}
	const loadLocationRoomList = () => {
		bizLocationRoomApi
			.bizLocationRoomList({
				areaId: formData.value.areaId,
				buildingId: formData.value.buildingId
			})
			.then((res) => {
				roomOptions.value = res.map((item) => {
					return {
						label: item.name,
						value: item.id
					}
				})
				if (res.length === 0) {
					//如果没有查找到房间，需要清空成null
					formData.value.roomId = null
				}
			})
	}
	const changeArea = () => {
		formData.value.roomId = null
		loadLocationRoomList()
	}
	const changeBuilding = () => {
		formData.value.roomId = null
		loadLocationRoomList()
	}
	// 关闭抽屉
	const onClose = () => {
		if (fromCabinetGroup.value) {
			formData.value = {
				cabinetGroupId: formData.value.cabinetGroupId
			}
		} else {
			formData.value = {}
		}
		formRef.value.resetFields()
		selectedAdminUsers.value = []
		visible.value = false
	}
	// 默认要校验的
	const formRules = {
		cabinetGroupId: [required('请选择组柜')],
		cabinetCode: [required('请输入柜子编号')],
		cabinetName: [required('请输入柜子名称')],
		cabinetTypeId: [required('请输入柜子类型')],
		adminUserIds: [required('请选择管理员')],
		makingInventoryUnit: [required('请选择盘库周期单位')],
		makingInventoryCycle: [required('请选择盘库周期')],
		cabinetIdentify: [required('请输入设备硬件标识')]
	}
	// 验证并提交数据
	const onSubmit = () => {
		formRef.value.validate().then(() => {
			submitLoading.value = true
			const formDataParam = cloneDeep(formData.value)
			bizCabinetInfoApi
				.bizCabinetInfoSubmitForm(formDataParam, !formDataParam.id)
				.then(() => {
					onClose()
					emit('successful')
				})
				.finally(() => {
					submitLoading.value = false
				})
		})
	}
	const filterOption = (input, option) => {
		if (option.label && input) {
			return option.label.toLowerCase().indexOf(input.toLowerCase()) >= 0
		}
		return null
	}

	const _useRouter = useRouter()

	watch(
		() => _useRouter.currentRoute.value,
		(newValue, oldValue) => {
			if (newValue.name === 'cabinetinfo') {
				let params = newValue.params
				console.log('---params=', params)
				fromCabinetGroup.value = true
				formData.value.cabinetGroupId = params.cabinetGroupId
			}
		},
		{
			immediate: true
		}
	)

	const changeCabinetGroup = (value,options) => {
		// console.log(value, options)
		formData.value.cabinetIdentify = options.cabinetIdentify
	}


	// 抛出函数
	defineExpose({
		onOpen
	})
</script>
